﻿chrome.extension.sendRequest({action : 'getOptions', title:document.title},function(response) {
var isAdmin = $('textarea').length > 0;
var isProfilePage = document.URL.indexOf('/profile')>0;
var opt = response;
//语音输入微博
if(isAdmin && opt && opt.options && opt.options.xSpeech)
{
	$('<input type="text" id="publish_editor_speech" style  onwebkitspeechchange="onwebkitspeech(this.value)" x-webkit-speech speech />').insertAfter('textarea');
	$(document.body).append('<script type="text/javascript">function onwebkitspeech(val){var pee = document.getElementsByTagName(\'textarea\')[0]; pee.value= pee.value + val;this.value=\'\';}</script>');
	$(document.body).append('<style>#publish_editor_speech{position: absolute;right: 3px;bottom: 5px;outline: none;border: none;background: rgba(255, 255, 255, 0);width:13px;height:19px;cursor:auto;}</style>');
	$(document.body).attr('lang', 'zh-Hans');
}

//隐藏右边
if(opt && opt.options && opt.options.hide)
{
    if(isAdmin || isProfilePage)
    {
        var rightNavs = $('.MIB_mblogbgl').find('.mainR>div:gt(0)');
        var hide = isAdmin ? opt.hide.admin.right : opt.hide.profile.right;
        rightNavs.each(function(index)
        {
            if($.inArray(index, hide) > -1)
            {
                $(this).css('display', 'none');
            }
        });
    }
}

//显示大图
if(opt.options.bigPic === true)
{
	/*
    $('img.bigcursor').each(function(){
		expandImg(this);
	});
    if(isAdmin)
    {
        setInterval(function(){
            $('img.bigcursor').each(function(){
                expandImg(this);
			});
		}, 200);
    }*/
	$('dd[node-type=feed_list_media_prev], ul[node-type=feed_list_media_prev]').each(function(){
		expandImg(this);
	});
    if(isAdmin)
    {
        setInterval(function(){
            $('dd[node-type=feed_list_media_prev], ul[node-type=feed_list_media_prev]').each(function(){
				expandImg(this);
			});
		}, 200);
    }
	function expandImg(preview)
	{
		var img = $(preview).find('img.bigcursor');
		var src = $(img).attr('src');
		if(src)
		{
			var midSrc = src.replace("/thumbnail/", "/bmiddle/");
			var bigSrc = src.replace("/thumbnail/", "/large/");
			$(preview).hide();
			var expand = $(preview).next();
			if(expand && expand.css('display') == 'none')
			{
				
				expand.append(['<p class="W_no_border"><a action-type="feed_list_media_toSmall" href="javascript:void(0);" class="retract">收起</a><i class="W_vline">|</i><a href="', bigSrc, '" target="_blank" class="show_big">查看大图</a><i class="W_vline">|</i><a action-type="feed_list_media_toLeft" href="javascript:void(0);" class="turn_left">向左转</a><i class="W_vline">|</i><a action-type="feed_list_media_toRight" href="javascript:void(0);" class="turn_right">向右转</a></p>'].join(''));
				expand.append(['<div class="smallcursor" action-type="feed_list_media_bigimgDiv"><img dynamic-id="',  (new Date).getTime(), '" action-type="feed_list_media_bigimg" src="', midSrc, '" width="440"></div>'].join(''));
				expand.show();
			}
		}
	}
}

//隐藏广告
if(opt.options.ad === true)
{
    $("a[class=close]").trigger("click");
}

//隐藏右边
if((isAdmin || isProfilePage) && opt.options.hide === true)
{
    $(document).ready(function(){
            var rightNavs = $('.MIB_mblogbgl').find('.mainR>div:gt(0)');//用户信息不隐藏
                    $(rightNavs).each(function(){
                        if($(this).css('display') != 'none'){
                            if($(this).text().indexOf('玩转微博') == -1)
                            {
                                $(this).prepend('<a style="display: none;float:right;width:48px;z-index:4;" href="javascript:void(0);" i=\'i\'>隐藏</a>');
                            }
                            else
                            {
                                $(this).find('a').parent().parent().prepend('<a style="display: none;float:right;width:48px;z-index:4;" href="javascript:void(0);" i=\'i\'>隐藏</a>');
                            }
                        }
                    });
            
        rightNavs.live('mouseenter', function(){
                        if($(this).css('display') == 'none')return;
                        if($(this).find('a[i=i]').length == 0)
                        {
                            $(this).prepend('<a style="display: none;float:right;width:48px;z-index:4;" href="javascript:void(0);" i=\'i\'>隐藏</a>');
                        }
                        var bgc = $(this).css('backgroundColor');
                        var c = 'red';
                        var obj = {'display': 'block', 'backgroundColor': bgc, 'color':c};
                        $(this).css({'border':'1px #333 solid'}).find('a[i=i]').css(obj);
                    }).live('mouseleave', function(){
                        if($(this).css('display') == 'none')return;
                        $(this).css({'border':'0px #333 solid'}).find('a[i=i]').css('display', 'none');
                    });
         rightNavs.each( function(index){
                                var r = $(this);
                                if(r.css('display') == 'none')return;
                                r.find('a[i=i]').live('click', function(){
                                chrome.extension.sendRequest({'action' : 'hide', 'ele':{'pos':'right', 'index':index, 'admin':isAdmin}}, onHide);
                                r.css('display', 'none');
                                function onHide(response)
                                {
                                }
                            });
                        });
        });
}
//隐藏右边

//草稿
if(opt.options.draft === true)
{
        var adHtmlArr = [];
        adHtmlArr.push("<div class=\"OnTit\" id=\"publisher_draft\">");
        adHtmlArr.push("<div id='btnDraft'>");
        adHtmlArr.push("<img title='草稿' id='imgDraft' class='small_icon' src='http://tjs.sjs.sinajs.cn/t3/style/images/common/transparent.gif' />");
        adHtmlArr.push("<a href=\"javascript:void(0);\">草稿</a>");
        adHtmlArr.push("</div>");
        adHtmlArr.push("</div>");
        var html = adHtmlArr.join("");
        $("#publisher_topic").parent().append(html);
        var draftHtml;
            chrome.extension.sendRequest({'action' : 'getDraft'}, onGotDraft);
            function onGotDraft(data)
            {
                draftHtml = data;
                $("body").append(draftHtml);
            }
            
        $("#existingDraft").find("ol>li").live('mouseenter', function()
            {
                $(this).find("a.close")
                .click(function()
                        {
                            var li = $(this).parent();
                            var index = li.attr("index");
                            chrome.extension.sendRequest({'action' : 'deleteDraft', 'index':index}, onDeletedDraft);
                            function onDeletedDraft(data)
                            {
                                li.remove();
                                if($("#existingDraft").find("ol>li").length == 0)
                                {
                                    $("#existingDraft").prev().hide();//title
                                    $("#existingDraft").next().hide();//edit button
                                    $("#existingDraft").html("草稿删除完毕，那就听听李健的<a href=\"http://music.sina.com.cn/yueku/m.php?id=371978&FLAG_ADDLIST=0\" target=\"_blank\" sm=\"music\">今生今世遥不可及<img class=\"small_icon musicico\" src=\"http://timg.sjs.sinajs.cn/miniblog2style/images/common/transparent.gif\"></a>放松一下。");
                                }
                            }
                        })
                .show();
            }).live("mouseleave", function()
            {
                $(this).find("a.close").hide();
            });
        
        
        $("#btnDraft").click(function()
        {
            chrome.extension.sendRequest({'action' : 'getDraftData'}, onGotDraftData);
            function onGotDraftData(response)
            {
                if(response.count == 0)
                {
                    $("#existingDraft").prev().hide();//title
                    $("#existingDraft").next().hide();//edit button
                }
                $("#existingDraft").html(response.data);
                
                
               var pos = $("#publisher_vote").offset();  
              var width = $("#btnDraft").width();
              var draftListWidth = $("#myDraftListx").width();
              var height = $("#btnDraft").height();
              $("#myDraftListx").css( {position: "absolute",marginLeft: 0, marginTop: 0, "left": (pos.left  - draftListWidth/2 + width*2) + "px", "top":(pos.top + height) + "px" } ).show();
            }
            
            $("#myDraftListxClose").click(function()
            {
                $("#myDraftListx").hide();
            });
        });
        
        var mouse_is_inside = false;
        $(document).ready(function()
        {
            $("#myDraftListx").live("mouseenter", function(){
            mouse_is_inside=true; 
            });
            $("#myDraftListx").live("mouseleave", function(){
            mouse_is_inside=false; 
            });

            $("body").mouseup(function(){ 
                if(! mouse_is_inside) $("#myDraftListx").hide();
            });

        });
        
        function saveDraft(autoSave, infoId, isNew)
        {
            var text = $("#publish_editor").val();
            if(text.length > 0)
            {
                var datetime = new Date();
                var h=datetime.getHours();
                var m=datetime.getMinutes();
                var s=datetime.getSeconds();
                var time = h+":"+m+":"+s;
                var index = 
                chrome.extension.sendRequest({'action' : 'saveDraft', text:text, time:datetime, isNew:isNew}, onSavedDraft);
                function onSavedDraft(data)
                {
                    if(autoSave)
                    {
                        $("#" + infoId).append("，草稿在" + time + "已保存");
                    }
                    else
                    {
                        $("#" + infoId).html("草稿已保存").show();
                        chrome.extension.sendRequest({'action' : 'getDraftData'}, onGotDraftData);
                        function onGotDraftData(response)
                        {
                            $("#existingDraft").html(response.data);
                            if(response.count > 0)
                            {
                                $("#existingDraft").prev().show();//title
                                $("#existingDraft").next().show();//edit button
                            }
                        }
                        
                        setTimeout(function(){
                            $("#" + infoId).html("").hide();
                        }, 2000);
                    }
                }
            }
        }
        
        $("#draftSave").live("click", function()
        {
            saveDraft(false, "saveInfo", true);
        });
        
        $("#editDraft").live("click", function()
        {
            var radio = $("#existingDraft").find("ol>li>input[name=v_draft]:checked");
            var draftLabel = radio.next();
            
            $("#publish_editor").val(draftLabel.text());
            draftLabel.next().trigger("click");//delete button
            draftLabel.parent().remove();
            $("#myDraftListx").hide();
        });
}

//草稿

$(document).ready(function(){
    //超140
    if(opt.options.nolimit === true)
    {
                $('#publisher_info').css('display','none');
                var remaining;
                $('#publisher_submit').mousedown(function()
                {
                    var text = $('#publish_editor').val();
                    var len = Core.String.getLength(text);
                    if(len <=140)return;
                    
                    var byteLen = Core.String.byteLength(text);
                    $('#publish_editor').val(Core.String.leftB(text, 280));
                    var sText = text.replace(/\*/g," ").replace(/[^\x00-\xff]/g,"**");
                    remaining = Core.String.subStr(text, 281, sText.length - 280);
                });
                
                $('#publisher_submit').mouseup(function()
                {
                    if(remaining && Core.String.getLength(remaining) <=0) return;
                    setTimeout(function(){
                            chrome.extension.sendRequest({'action' : 'publish', text:remaining}, onPublished);
                            function onPublished()
                            {
                            }
                        },2000);
                });
    }
    //超140

//快捷
if(opt.options.shortcut)
{
//http://userscripts.org/scripts/review/61163
$(function(){
    twttr={};
    twttr.shortcuts={};
		    (function () {
	            twttr.shortcuts.currentKey = null;
	            var A = [];
	            var B = {
	                71: "g",
	                85: "u",//fav
	                84: "t",//at
	                73: "i",//profile
	                72: "h",//home
	                78: "n",//comments
	                48: "0"
	            };
	            $(document).keydown(function (C) {
	                if (twttr.shortcuts.verify(C) && $(C.target).is(":not(input)")) {
	                    C.preventDefault()
	                } else {
	                    twttr.shortcuts.currentKey = null
	                }
	            });
	            twttr.shortcuts.combo=function (D, C) {
	                A.push({
	                    keys: D,
	                    fn: C
	                })
	            };
	            twttr.shortcuts.verify = function (F) {
	                var G = F.keyCode;
	                var C = false;
	                for (var D = 0; D < A.length; D++) {
	                    var E = A[D];
	                    if (B[G] === E.keys[0]) {
	                        C = true;
	                        twttr.shortcuts.currentKey = B[G];
	                        break
	                    } else {
	                        if (B[G] === E.keys[1] && twttr.shortcuts.currentKey === E.keys[0]) {
	                            C = true;
	                            twttr.shortcuts.currentKey = null;
	                            E.fn();
	                            break
	                        }
	                    }
	                }
	                return C
	            }
	        }());
            addShortcuts();
            twttr.shortcuts.combo(["g", "h"], function () {
	            window.location.href = 'http://t.sina.com.cn';
	        });
            twttr.shortcuts.combo(["g", "i"], function () {
	            $('div.head_menu').find('a').each(function(){
	                if($(this).text().indexOf('我的微博') > -1)
	                {
	                    window.location.href = $(this).attr('href');
	                    return false;
	                }
	            });
	        });
	        twttr.shortcuts.combo(["g", "t"], function () {
	            window.location.href = 'http://t.sina.com.cn/atme';
	        });
	        twttr.shortcuts.combo(["g", "n"], function () {
	            window.location.href = 'http://t.sina.com.cn/comments';
	        });
	        twttr.shortcuts.combo(["g", "u"], function () {
	            window.location.href = 'http://t.sina.com.cn/favs';
	        });	
	        twttr.shortcuts.combo(["g", "0"], function () {
	            if($('#cutsDesc').length == 0)
	            {
	                var cuts = [];
	                cuts.push('<div style=\'display:none;position:absolute;z-index:99998;background-color: black;\' id=cutsDesc>');
	                cuts.push('</div>');
	                cuts.push('<span id=cutsContent style=\'background-color: white;opacity:1;z-index:99999;padding:6px\'>');
	                cuts.push('<font style="font-size: 25px; color: #000000; font-weight: bold; background-color: #00FFFF;">快捷键</font>');
	                cuts.push('<a id=\'closeCuts\' style=\'background-color: red;float:right;cursor:pointer\' title=\'Close\'>X</a><br/>');
	                cuts.push('<font style="font-size: 20px; font-weight: bold; color: #000000">微博操作</font>');
	                cuts.push('<ul style="font-size:15px">');
	                cuts.push('<li>x: 选中上条微博</li>');
	                cuts.push('<li>shift + x: 选中下条微博</li>');
	                cuts.push('<li>z: 转发选中微博</li>');
	                cuts.push('<li>f 或 p: 写微博(新浪提供)</li>');
	                cuts.push('<li>r: 刷新微博(新浪提供)</li>');
	                cuts.push('<li>ctrl + enter: 发表微博/评论(新浪提供)</li>');
	                cuts.push('</ul><font style="font-size: medium; font-weight: bold; color: #000000">导航</font>');
	                cuts.push('<ul style="font-size:15px">');
	                cuts.push('<li>m: 搜索</li>');
	                cuts.push('<li>j: 向上滚动(新浪提供)</li>');
	                cuts.push('<li>k: 向下滚动(新浪提供)</li>');
	                cuts.push('<li>g + h: 我的首页</li>');
	                cuts.push('<li>g + i: 我的微博</li>');
	                cuts.push('<li>g + u: 我的收藏</li>');
	                cuts.push('<li>g + t: @提到我的</li>');
	                cuts.push('<li>g + n: 我的评论</li>');
	                cuts.push('</ul>');
	                cuts.push('</span>');
	                $('body').append(cuts.join(''));
	            }
	            $('#cutsDesc').css({height:$('body').height(), width:$('body').width(), top:'0px', left:'0px', "opacity":"0.6"}).show();
	            var windowWidth = document.documentElement.clientWidth;
                var windowHeight = document.documentElement.clientHeight;
                var popupHeight = $("#cutsContent").height();
                var popupWidth = $("#cutsContent").width();
                //centering
                $('#cutsContent').css({
                    "position": "absolute",
                    "top": windowHeight/2-popupHeight/2,
                    "left": windowWidth/2-popupWidth/2
                }).show();
                window.scrollTo(0, $('#cutsContent').scrollTop());
                
                $('#closeCuts').click(function()
                {
                    $('#cutsContent').hide();
                    $('#cutsDesc').hide();
                });
                shortcut.add("esc",function() {
                    $('#cutsContent').hide();
                    $('#cutsDesc').hide();
                });
	        });	
		var hasSelected = false;
        var selectedFeedId;
        function selectFeed(next)
        {
            var nextFeed;
            if(hasSelected === false)
            {
                $('ul.MIB_feed>li:eq(0)').css({'background-color': '#D0F1F6'});
                hasSelected = true;
                nextFeed = next === true ? $('ul.MIB_feed>li:first') : $('ul.MIB_feed>li:last');
                selectedFeedId = nextFeed.attr('id');
                window.scrollTo(0, nextFeed.scrollTop());
            }
            else
            {
                var curFeed = $('#' + selectedFeedId)[0];
                 nextFeed = next===true ? $('#' + selectedFeedId).next() : $('#' + selectedFeedId).prev();
                if(nextFeed.length > 0)
                { curFeed.style.backgroundColor = 'white';
                    selectedFeedId = nextFeed.attr('id');
                    nextFeed.css({'background-color': '#D0F1F6'});
                    var scrollH = nextFeed.height();
                    window.scrollTo(0, next ? $(document).scrollTop() + scrollH : $(document).scrollTop() - scrollH);
                }
            }
        }
		shortcut.add("X",function() {
			selectFeed(true);
		});
		shortcut.add("Shift+X",function() {
		    selectFeed(false);
		});
		shortcut.add("Z",function() {
            if(selectedFeedId)
            {
                $('#' + selectedFeedId).find('a').each(function()
                {
                    if($(this).text().indexOf('转发') > -1)
                    {
                        $(this).trigger('click');
                        return false;
                    }
                });
            }
		});
    shortcut.add("M",function() {
            $('#m_keyword').focus();
        });
//      }
});

	function addShortcuts(){
		/**
		 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
		 * Version : 2.01.B
		 * By Binny V A
		 * License : BSD
		 */
		shortcut = {
			'all_shortcuts':{},//All the shortcuts are stored in this array
			'add': function(shortcut_combination,callback,opt) {
				//Provide a set of default options
				var default_options = {
					'type':'keydown',
					'propagate':false,
					'disable_in_input':true,
					'target':document,
					'keycode':false
				}
				if(!opt) opt = default_options;
				else {
					for(var dfo in default_options) {
						if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
					}
				}

				var ele = opt.target;
				if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
				var ths = this;
				shortcut_combination = shortcut_combination.toLowerCase();

				//The function to be called at keypress
				var func = function(e) {
					e = e || window.event;
					
					if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
						var element;
						if(e.target) element=e.target;
						else if(e.srcElement) element=e.srcElement;
						if(element.nodeType==3) element=element.parentNode;
						if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA' || element.tagName == 'SELECT') return;
					}
			
					//Find Which key is pressed
					if (e.keyCode) code = e.keyCode;
					else if (e.which) code = e.which;
					var character = String.fromCharCode(code).toLowerCase();
					
					if(code == 188) character=","; //If the user presses , when the type is onkeydown
					if(code == 190) character="."; //If the user presses , when the type is onkeydown

					var keys = shortcut_combination.split("+");
					//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
					var kp = 0;
					
					//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
					var shift_nums = {
						"`":"~",
						"1":"!",
						"2":"@",
						"3":"#",
						"4":"$",
						"5":"%",
						"6":"^",
						"7":"&",
						"8":"*",
						"9":"(",
						"0":")",
						"-":"_",
						"=":"+",
						";":":",
						"'":"\"",
						",":"<",
						".":">",
						"/":"?",
						"\\":"|"
					}
					//Special Keys - and their codes
					var special_keys = {
						'esc':27,
						'escape':27,
						'tab':9,
						'space':32,
						'return':13,
						'enter':13,
						'backspace':8,
			
						'scrolllock':145,
						'scroll_lock':145,
						'scroll':145,
						'capslock':20,
						'caps_lock':20,
						'caps':20,
						'numlock':144,
						'num_lock':144,
						'num':144,
						
						'pause':19,
						'break':19,
						
						'insert':45,
						'home':36,
						'delete':46,
						'end':35,
						
						'pageup':33,
						'page_up':33,
						'pu':33,
			
						'pagedown':34,
						'page_down':34,
						'pd':34,
			
						'left':37,
						'up':38,
						'right':39,
						'down':40,
			
						'f1':112,
						'f2':113,
						'f3':114,
						'f4':115,
						'f5':116,
						'f6':117,
						'f7':118,
						'f8':119,
						'f9':120,
						'f10':121,
						'f11':122,
						'f12':123
					}
			
					var modifiers = { 
						shift: { wanted:false, pressed:false},
						ctrl : { wanted:false, pressed:false},
						alt  : { wanted:false, pressed:false},
						meta : { wanted:false, pressed:false}	//Meta is Mac specific
					};
		                        
					if(e.ctrlKey)	modifiers.ctrl.pressed = true;
					if(e.shiftKey)	modifiers.shift.pressed = true;
					if(e.altKey)	modifiers.alt.pressed = true;
					if(e.metaKey)   modifiers.meta.pressed = true;
		                        
					for(var i=0; k=keys[i],i<keys.length; i++) {
						//Modifiers
						if(k == 'ctrl' || k == 'control') {
							kp++;
							modifiers.ctrl.wanted = true;

						} else if(k == 'shift') {
							kp++;
							modifiers.shift.wanted = true;

						} else if(k == 'alt') {
							kp++;
							modifiers.alt.wanted = true;
						} else if(k == 'meta') {
							kp++;
							modifiers.meta.wanted = true;
						} else if(k.length > 1) { //If it is a special key
							if(special_keys[k] == code) kp++;
							
						} else if(opt['keycode']) {
							if(opt['keycode'] == code) kp++;

						} else { //The special keys did not match
							if(character == k) kp++;
							else {
								if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
									character = shift_nums[character]; 
									if(character == k) kp++;
								}
							}
						}
					}
					
					if(kp == keys.length && 
								modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
								modifiers.shift.pressed == modifiers.shift.wanted &&
								modifiers.alt.pressed == modifiers.alt.wanted &&
								modifiers.meta.pressed == modifiers.meta.wanted) {
						callback(e);
			
						if(!opt['propagate']) { //Stop the event
							//e.cancelBubble is supported by IE - this will kill the bubbling process.
							e.cancelBubble = true;
							e.returnValue = false;
			
							//e.stopPropagation works in Firefox.
							if (e.stopPropagation) {
								e.stopPropagation();
								e.preventDefault();
							}
							return false;
						}
					}
				}
				this.all_shortcuts[shortcut_combination] = {
					'callback':func, 
					'target':ele, 
					'event': opt['type']
				};
				//Attach the function with the event
				if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
				else if(ele.attachEvent) ele.attachEvent('on' +opt['type'], func);
				else ele['on' +opt['type']] = func;
			},

			//Remove the shortcut - just specify the shortcut and I will remove the binding
			'remove':function(shortcut_combination) {
				shortcut_combination = shortcut_combination.toLowerCase();
				var binding = this.all_shortcuts[shortcut_combination];
				delete(this.all_shortcuts[shortcut_combination])
				if(!binding) return;
				var type = binding['event'];
				var ele = binding['target'];
				var callback = binding['callback'];

				if(ele.detachEvent) ele.detachEvent('on' +type, callback);
				else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
				else ele['on' +type] = false;
			}
		};
  }
}
//快捷

});
});

